import React, { useState, useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import TableTitle from '@/components/TableTitle';
import { Modal, message, Button, Descriptions, Result, Popconfirm } from 'antd';
import ProForm, {
  StepsForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormDigit,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import { columnsData, IPFSColumns } from './data';
import type {
  columnsDataType,
  contractTemplateType,
  ContractTemplateInfosType,
  IPFSListItem,
} from './data.d';
// 接口
import {
  getPositionGrades,
  createPositionGrade,
  getPositionIPFSList,
  mintPosition,
  getPosition,
  deletePositionGrade,
} from './service';
import { getContractTemplates } from '@/services/services';

/**
 *  getIsLoad
 *父组件的方法，用于点击详情的时候改变状态，写在铸造组件加载详情组件
 */
export default ({ setIsLoadCastingDetail, setPositionInfo }) => {
  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;
  const formRef = useRef<ProFormInstance>();
  // 控制铸造模态框
  const [isCastingModal, setIsCastingModal] = useState(false);
  const [addIdentityModal, setAddIdentityModal] = useState(false);
  // 倒计时
  const [countDown, setCountDown] = useState(3);
  // 新增身份等级信息
  const [newIdentityInfo, setNewIdentityInfo] = useState({});
  // 新增身份类型
  const [newIdentityType, setNewIdentityType] = useState<number>();
  // 铸造身份信息
  const [identityInfo, setIdentityInfo] = useState<columnsDataType>();
  // 合约规则列表
  const [contractTemplate, setContractTemplate] = useState<
    contractTemplateType[]
  >([]);
  // 铸造信息
  const [mintPositionInfo, setMintPositionInfo] = useState({});

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      {record.status === '0' ? (
        <>
          <li>
            <a
              onClick={async () => {
                setIdentityInfo(record);
                let res = await getContractTemplates({});
                console.log(res);
                setContractTemplate(
                  res.data.map((item: ContractTemplateInfosType) => {
                    const { templateCode: label, serialNo: value } = item;
                    return {
                      label,
                      value,
                    };
                  }),
                );
                toCast();
              }}
            >
              元数据配置
            </a>
            <em className="ant-list-item-action-split"></em>
          </li>
          <li>
            <Popconfirm
              title="确认删除此身份?"
              onConfirm={async () => {
                let res = await deletePositionGrade({
                  serialNo: record.serialNo,
                });
                console.log(res);
                if (res.code === '000000') message.success('删除成功');
                actionRef.current?.reload();
              }}
              okText="确认"
              cancelText="取消"
            >
              <a key={record.acNo}>删除</a>
            </Popconfirm>
          </li>
        </>
      ) : (
        <li>
          <a
            onClick={async () => {
              let res = await getPosition({});
              console.log(res);
              setIsLoadCastingDetail(true);
              setPositionInfo(record);
            }}
          >
            详情
          </a>
        </li>
      )}
    </ul>
  );

  // 自定义proTable数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();

  /**
   * 点击上传调用
   */
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      // setUploadLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      console.log(info);
      // setImageUrl(info.file.response.data.url);
      // setUploadLoading(false);
      setNewIdentityInfo({ gradeCover: info.file.response.data.url });
      return info.file.response.data.url;
    }
  };

  // 铸造按钮调用
  const toCast = () => {
    setIsCastingModal(true);
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title="身份铸造" />}
        scroll={{ x: 900 }}
        bordered
        // 表头
        columns={columns}
        actionRef={actionRef}
        // 请求获取的数据
        request={async (params) => {
          let res = await getPositionGrades({});
          console.log(res);
          const result = {
            data: res.data,
          };
          return result;
        }}
        rowKey="code"
        // 搜索表单的配置--关闭
        search={false}
        form={{
          ignoreRules: false,
        }}
        // pagination={{
        //   pageSize: 10,
        // }}
        toolBarRender={() => [
          <Button
            onClick={() => {
              setAddIdentityModal(true);
            }}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新增身份等级
          </Button>,
        ]}
      />
      {/* 添加身份 */}
      <StepsForm
        formRef={formRef}
        //  完成回调 value为填写的表单的信息
        onFinish={async (values) => {
          console.log(values);
          // 关闭模态框
          // setIsCastingModal(false);
          // true最后一步重置表单，回到第一步
          return true;
        }}
        // 表单验证规则
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        // 自定义整个表单区域，返回的 dom 在表单的外部
        stepsFormRender={(dom, submitter) => {
          return (
            <Modal
              title="等级添加"
              width={900}
              onCancel={() => setAddIdentityModal(false)}
              visible={addIdentityModal}
              footer={submitter}
              centered
            >
              {dom}
            </Modal>
          );
        }}
        // 自定义按钮
        submitter={{
          render: (props) => {
            if (props.step === 0) {
              return (
                <Button type="primary" onClick={() => props.onSubmit?.()}>
                  下一步 {'>'}
                </Button>
              );
            }

            if (props.step === 1) {
              return [
                <Button key="pre" onClick={() => props.onPre?.()}>
                  上一步
                </Button>,
                <Button
                  type="primary"
                  key="goToTree"
                  onClick={() => props.onSubmit?.()}
                >
                  确定
                </Button>,
              ];
            }

            return null;
          },
        }}
      >
        {/* 一 身份信息*/}
        <StepsForm.StepForm
          name="base"
          title="身份信息"
          onFinish={async (value) => {
            console.log(value);

            setNewIdentityInfo({
              grade: 0,
              ...newIdentityInfo,
              ...value,
            });
            // 点击下一步回调
            return true;
          }}
        >
          <ProFormText
            name="name"
            label="身份名称(需与身份元数据对应)"
            placeholder="请输入等级名称"
            rules={[{ required: true }]}
          />
          <ProFormText
            name="code"
            label="身份编号"
            placeholder="请输入等级编号"
            rules={[{ required: true }]}
          />
          <ProFormUploadButton
            extra="支持扩展名：.jpg .png"
            label="身份封面"
            max={1}
            action="http://114.116.93.253:8097/aliUpload"
            name="file"
            title="上传图片"
            onChange={handleChange}
          />
          <ProFormSelect
            name="gradeType"
            label="身份类型"
            placeholder="请选择身份类型"
            rules={[{ required: true }]}
            fieldProps={{
              onChange: (e) => {
                setNewIdentityType(e);
                if (e == 0) {
                  console.log(e);
                }
              },
            }}
            options={[
              {
                label: '创世',
                value: 0,
              },
              {
                label: '普通',
                value: 1,
              },
            ]}
          />
          {newIdentityType ? (
            <ProFormDigit
              name="grade"
              label="身份等级"
              min={1}
              placeholder="请输入身份等级"
              rules={[{ required: true }]}
            />
          ) : null}
          <ProFormDigit
            name="totalSupply"
            label="总供应量"
            placeholder="请输入总供应量"
            rules={[{ required: true }]}
          />
          <ProFormTextArea
            name="description"
            label="身份描述"
            placeholder="请输入等级描述"
            rules={[{ required: true }]}
          />
        </StepsForm.StepForm>
        {/* 二 选择配置*/}
        <StepsForm.StepForm
          name="checkbox"
          title="达成条件"
          onFinish={async (values) => {
            let res = await createPositionGrade({
              ...newIdentityInfo,
              ...values,
            });
            console.log(res);
            if (res.code === '000000') {
              // console.log(dataSource);
              message.success('添加成功');
              let a = countDown;
              let countDowns = setInterval(() => {
                setCountDown(a - 1);
                a = a - 1;
                if (a === 0) {
                  console.log(a);
                  setAddIdentityModal(false);
                  formRef.current?.submit();
                  setCountDown(3);
                  clearInterval(countDowns);
                  // 表格重新渲染
                  actionRef.current?.reload();
                }
              }, 1000);
              return true;
            }
          }}
        >
          <ProFormDigit
            name="fs"
            label="拥有火源不少于"
            placeholder="请输入火源数量"
            rules={[{ required: true }]}
          />
          <ProFormDigit
            name="fc"
            label="拥有原力不少于"
            placeholder="请输入原力数量"
            rules={[{ required: true }]}
          />
          <ProFormDigit
            name="reputation"
            label="拥有声誉不少于"
            placeholder="请输入声誉数量"
            rules={[{ required: true }]}
          />
        </StepsForm.StepForm>
        {/* 三 添加完成*/}
        <StepsForm.StepForm name="time" title="添加完成">
          <Result status="success" title="添加成功！" />
          <span
            style={{
              display: 'inline-block',
              width: '100%',
              textAlign: 'center',
            }}
          >
            {countDown}秒后退出
          </span>
        </StepsForm.StepForm>
      </StepsForm>
      {/* 铸造模态框 */}
      <StepsForm
        formRef={formRef}
        onFinish={async (values) => {
          setIsCastingModal(false);
          return true;
        }}
        // 表单验证规则
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        // 自定义整个表单区域，返回的 dom 在表单的外部
        stepsFormRender={(dom, submitter) => {
          return (
            <Modal
              title="身份铸造"
              width={900}
              onCancel={() => setIsCastingModal(false)}
              visible={isCastingModal}
              footer={submitter}
              destroyOnClose
              centered
            >
              {dom}
            </Modal>
          );
        }}
        // 自定义按钮
        submitter={{
          render: (props) => {
            if (props.step === 0) {
              return (
                <Button type="primary" onClick={() => props.onSubmit?.()}>
                  下一步 {'>'}
                </Button>
              );
            }

            if (props.step === 1) {
              return [
                <Button key="pre" onClick={() => props.onPre?.()}>
                  上一步
                </Button>,
                <Button
                  type="primary"
                  key="goToTree"
                  onClick={() => props.onSubmit?.()}
                >
                  确定
                </Button>,
              ];
            }

            return null;
          },
        }}
      >
        {/* 一 信息展示*/}
        <StepsForm.StepForm
          name="base"
          title="信息展示"
          onFinish={async (values) => {
            setMintPositionInfo({
              ...values,
            });
            // 点击下一步回调
            return true;
          }}
        >
          <h2 style={{ fontSize: 14, color: '#222', marginBottom: 16 }}>
            身份信息
          </h2>
          <Descriptions>
            <Descriptions.Item label="名称">
              {identityInfo?.name}
            </Descriptions.Item>
            <Descriptions.Item label="等级">
              {identityInfo?.grade}
            </Descriptions.Item>
            <Descriptions.Item label="数量">
              {identityInfo?.totalSupply}
            </Descriptions.Item>
          </Descriptions>
          {/* 合约模板 */}
          <ProForm.Group title="合约模板">
            <ProFormSelect
              name="contractTemplateNo"
              fieldProps={{
                style: {
                  minWidth: 180,
                },
              }}
              options={contractTemplate}
            />
          </ProForm.Group>
        </StepsForm.StepForm>
        {/* 二 选择配置*/}
        <StepsForm.StepForm
          name="checkbox"
          title="身份元数据"
          onFinish={async (values) => {
            const { name: metadataName, grade: positionGrade } = identityInfo;
            let res = await mintPosition({
              ...mintPositionInfo,
              metadataName,
              positionGrade,
            });
            console.log(res);
            if (res.code === '000000') {
              message.success('成功');
              let a = countDown;
              let countDowns = setInterval(() => {
                setCountDown(a - 1);
                a = a - 1;
                if (a === 0) {
                  console.log(a);
                  setAddIdentityModal(false);
                  formRef.current?.submit();
                  setCountDown(3);
                  clearInterval(countDowns);
                  // 表格重新渲染
                  actionRef.current?.reload();
                }
              }, 1000);
              return true;
            }
          }}
        >
          {/* 元数据列表 */}
          <ProTable<IPFSListItem>
            columns={IPFSColumns}
            scroll={{ x: 800 }}
            // 请求获取的数据
            request={async (params) => {
              const { name: metadataName, grade } = identityInfo;
              let { data } = await getPositionIPFSList({
                ...params,
                metadataName,
                grade,
              });
              console.log(data);
              const result = {
                data,
              };
              return result;
            }}
            rowKey="serialNo"
            pagination={{
              showQuickJumper: true,
            }}
            search={false}
            dateFormatter="string"
            headerTitle="元数据"
            toolBarRender={false}
          />
        </StepsForm.StepForm>
        {/* 三 铸造完成*/}
        <StepsForm.StepForm name="time" title="完成">
          <Result
            status="success"
            title="成功！"
            subTitle="欢迎使用Bigan数字资产管理平台"
          />
          <span
            style={{
              display: 'inline-block',
              width: '100%',
              textAlign: 'center',
            }}
          >
            {countDown}秒后退出
          </span>
        </StepsForm.StepForm>
      </StepsForm>
    </div>
  );
};
